package com.lexed.carmanager.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.lexed.carmanager.database.MybatisApplication;
import com.lexed.carmanager.database.mapping.DriverMapper;
import com.lexed.carmanager.database.pojo.Driver;

import net.minidev.json.JSONObject;

public class DriverService {

	
	
	
	public List<Driver> showAll(){
		// 获取sqlsession
		SqlSession sqlSession = MybatisApplication.openSession();
		// 获取mapper对象
		DriverMapper driverMapper = sqlSession.getMapper(DriverMapper.class);
				
		List<Driver> list = driverMapper.selectAll();
		
		sqlSession.close();
		
		return list;
	}
	
	// 2\登录等方法
	public String login(String username, String password){
		// 获取sqlsession
		SqlSession sqlSession = MybatisApplication.openSession();
		// 获取mapper对象
		DriverMapper driverMapper = sqlSession.getMapper(DriverMapper.class);
		
		Driver user = driverMapper.selectByUsername(username);
		
		JSONObject json = new JSONObject();
		//  "" 空的字符串 有地址的 是一个对象 不为null
		//  null 没有内存地址
		
		if( user!=null && 
				(user.getPassword() == null || "".equals(user.getPassword().trim()))){
			// 需要填写密码
			json.put("status", 0);
			json.put("msg", "初始化用户密码");
			json.put("id",user.getId());
		}else if(user!=null && user.getPassword().equals(password)){
			json.put("status", 1);
			json.put("msg", "登录成功");
			json.put("username", user.getUsername());
			json.put("rolm", user.getRolm());
			// 权限
			// 登录成功
		}else{
			json.put("status", 2);
			json.put("msg", "用户名或密码错误");
			// 登录不成功
		}
		// 关闭会话
		sqlSession.close();
		return json.toJSONString();
	}
	
	// 3、重置密码
	public int repwd(int id, String password){
		SqlSession sqlSession = MybatisApplication.openSession();
		DriverMapper driverMapper = sqlSession.getMapper(DriverMapper.class);
		
		// 用id和password 创建Driver对象
		Driver driver = new Driver();
		driver.setId(id);
		driver.setPassword(password);
		// 进行数据库内容的修改
		int re = driverMapper.updateByPrimaryKeySelective(driver);
		
		sqlSession.close();
		return re;
	}
	
	// 添加用户
	public int addUser(Driver driver){
		SqlSession sqlSession = MybatisApplication.openSession();
		DriverMapper driverMapper = sqlSession.getMapper(DriverMapper.class);
		
		int re = driverMapper.insertSelective(driver);
		
		sqlSession.close();
		
		return re;
		
	}

}
